package com.wujunshen.redis.support;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;

/**
 * User:Administrator(吴峻申) <br>
 * Date:2016-8-11 <br>
 * Time:14:57 <br>
 * Mail:frank_wjs@hotmail.com <br>
 */
public final class PropertySourcesSupport {
    private PropertySourcesSupport() {
        //
    }

    /**
     * 检查配置文件中是否包含某个前缀
     *
     * @param env    应用环境
     * @param prefix 要判断的前缀值
     * @return true为包含，false为不包含
     */
    public static boolean containsPropertyNamePrefix(Environment env, String prefix) {
        if (env instanceof ConfigurableEnvironment) {
            for (PropertySource<?> propertySource :
                    ((ConfigurableEnvironment) env).getPropertySources()) {
                if (containsNamePrefix(propertySource, prefix)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @param propertySource 配置类
     * @param prefix         要判断的前缀值
     * @return true为包含，false为不包含
     */
    private static boolean containsNamePrefix(PropertySource<?> propertySource, String prefix) {
        if (propertySource instanceof EnumerablePropertySource) {
            for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                if (key.startsWith(prefix)) {
                    return true;
                }
            }
        }
        return false;
    }
}